package lucene.server.web.controller.admin;


import lombok.extern.slf4j.Slf4j;
import lucene.server.common.model.Result;
import lucene.server.common.model.TaskConfig;
import lucene.server.common.utils.CronUtil;
import lucene.server.common.utils.StringUtil;
import lucene.server.web.dao.SystemDao;
import lucene.server.web.task.SQLTask;
import lucene.server.web.task.TaskPool;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.UUID;


@RestController
@RequestMapping("/admin/task")
@Slf4j
public class TaskController {

    //todo 增删改查对应的taskPool的操作没有实现

    @GetMapping(value = "/get")
    public Result<?> getCron(HttpServletRequest req) throws SQLException {
        return  Result.OK(SystemDao.getAll("task", TaskConfig.class));
    }
    @PostMapping(value = "/update")
    public Result<?> updateCron(@RequestBody TaskConfig taskConfig, HttpServletRequest req) {

        String error = checkTask(taskConfig);
        if (!StringUtil.isEmpty(error)){
            return Result.error(error);
        }
        //如果id没有，先判断是否存在
        if (StringUtil.isEmpty(taskConfig.getId()) && SystemDao.checkExists(taskConfig, "name")) {
            return Result.error("任务名称已存在");
        }
        if (StringUtil.isEmpty(taskConfig.getId())){
            taskConfig.setId( UUID.randomUUID().toString().replace("-", ""));
        }else{
            TaskConfig oldConfig = SystemDao.findOne(taskConfig, TaskConfig.class);
            TaskPool.shutdown("sql_"+oldConfig.getName());
        }
        SystemDao.insertOrUpdate(taskConfig);
        SQLTask sqlTask = new SQLTask(taskConfig);
        TaskPool.addTask(sqlTask);
        return Result.OK();
    }

    @PostMapping(value = "/runTask")
    public Result<?> runTask(@RequestBody TaskConfig task, HttpServletRequest req) {
        TaskPool.runTask("sql_"+task.getName());
        return Result.OK();
    }

    @PostMapping(value = "/delete")
    public Result<?> deleteCron(@RequestBody TaskConfig task, HttpServletRequest req) {
        SystemDao.delete(task);
        //todo 到时候删除相关的具体任务
        TaskPool.shutdown("sql_"+task.getName());
        return Result.OK();
    }
    @GetMapping(value = "/checkCron")
    public Result<?> checkCron(@RequestParam(name = "cron",required = true,defaultValue = "")String cron,HttpServletRequest req) throws SQLException {
        return  Result.OK(CronUtil.translateToChinese(cron));
    }
    private String checkTask(TaskConfig task){
        String error = "";
        error += StringUtil.assertNull(task.getName(),"名称不能为空\n");
        error += StringUtil.assertNull(task.getIndexName(),"索引不能为空\n");
        error += StringUtil.assertNull(task.getDbsql(),"SQL语句不能为空\n");
        error += StringUtil.assertNull(String.valueOf(task.getType()),"类型不能为空\n");
        return error;
    }

}

